//
//  QDSettingViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/22.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 设置控制器
final class QDSettingViewController: QDLargeTitleViewController {
    
    /// 所有的标题
    override var titles: [String] {
        get {
            return allTitles
        }
    }
    
    /// 所有的副标题
    override var subtitles: [String]{
        get {
            // 需要控制kingfisher的文件大小
            return ["","\(SDImageCache.shared().getSize().sizeString)","","当前版本\(NSDictionary.ritl_version ?? "")"]
        }
    }
    
    /// 所有的标题
    fileprivate let allTitles = ["消息免打扰","清理缓存","了解青岛地铁","关于"]
    let logoutTableFooterView = QDSettingLogoutFooterView()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        largeTableHeaderView.title = "设置"

        if QDUserStatus.isLogin {
            
            logoutTableFooterView.frame = CGRect(origin: .zero, size: CGSize(width: ritl_width, height: 88))
            tableView.tableFooterView = logoutTableFooterView
            
            logoutTableFooterView.logoutButton.addTarget(self, action: #selector(logoutButtonDidTap), for: .touchUpInside)
        }
    }
    
    /// 退出按钮点击
    @objc func logoutButtonDidTap(){
        
        QDUserStatus.isLogin = false/// 登出
        navigationController?.popViewController(animated: true)
    }


    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let title = titles[indexPath.row]
        
        ///  打开设置
        func openSetting(){
            if let url = URL(string:UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url){
                UIApplication.shared.openURL(url); return
            }
            
            // 弹出alert
            let alertController = UIAlertController(title: "请到-“设置“-“通知”-“青岛地铁”中开启", message: nil, preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil))
            present(alertController, animated: true, completion: nil)
        }
        
        /// 清除图片缓存
        func clearImageCache(){
            SDImageCache.shared().clearDisk {
                tableView.reloadData()
            }
        }
        
        /// 打开关于地铁的web
        func openAboutWeb(){
            pushToWebViewController(url: "http://site.qd-metro.com/about_us", autoTitle: false, title: "青岛地铁", qdmetro: true)
        }
            
        
        switch title {
            
        case "消息免打扰": openSetting()
        case "清理缓存": clearImageCache()
        case "了解青岛地铁": openAboutWeb()
        case "关于": ritl_topNavigationPush(QDAboutViewController(), animated: true)
            
        default: return
        }
    }
}
